//
// Created by tang on 2022/1/11.
//

#include "management_view.hpp"
#include "data/sql_stores.hpp"
#include "gui/ui_component.hpp"
#include "imgui/imgui.h"
#include "imgui/imgui_stdlib.h"
#include "imgui/IconsFontAwesome4.h"
#include "gui/controls/custom_controls.hpp"
#include "app/app_base.hpp"
#include "dexode/eventbus/Listener.hpp"
#include "event/events.hpp"
#include "sql/types.hpp"

struct ManagementData
{
    bool need_reload_tags{ true };
    bool is_processing{ false };
    // std::vector<Tag> all_tags;
    Tag* current_tag{ nullptr };
    Tag  tag_copy{};
    std::string new_tag_label;
    uint32_t new_tag_level{ L_PRIMARY };
    float tag_color[3]{ 0.2f,0.2f,0.2f };
    float tag_color_copy[3]{ 0.f };
};

ManagementView::ManagementView() : d{ new ManagementData }
{
}

ManagementView::~ManagementView()
{
    delete d;
}

unsigned int ManagementView::Flags() const
{
    return eDialog;
}

void ManagementView::RenderContent(ComponentFlag flag)
{
    if (flag == eDialog)
        Dialog();
}

const char* ManagementView::GetName(ComponentFlag flag)
{
    if (flag == eDialog)
        return MODAL_DIALOG_NAME(TAG_MANAGEMENT_DIALOG_NAME);
    return nullptr;
}

void ManagementView::Dialog()
{
    ImGuiID editor_id = ImGui::GetID("编辑标签##TagEditor");

    ImGui::SetNextItemWidth(250);
    ImGui::InputTextWithHint("##TagField", "输入新标签...", &d->new_tag_label);
    ImGui::SameLine();
    ImGui::ColorEdit3("标签颜色", d->tag_color, ImGuiColorEditFlags_Float | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_NoInputs);
    ImGui::SameLine();
    bool checked = d->new_tag_level == L_PRIMARY;
    if (ImGui::Checkbox("是否为一级标签？", &checked))
    {
        if (checked)
            d->new_tag_level = L_PRIMARY;
        else
            d->new_tag_level = L_SECONDARY;
    }
    ImGui::SameLine();
    ImGui::BeginDisabled(d->new_tag_label.empty() || d->is_processing);
    if (ImGui::Button(ICON_FA_PLUS_CIRCLE " 添加"))
    {
        d->is_processing = true;
        App->Async([this]
            {
                const Tag tag = App->Sql()->NewTag(d->new_tag_label, ImU32(ImColor(d->tag_color[0], d->tag_color[1], d->tag_color[2])), d->new_tag_level);
                if (tag.tag_id > 0)
                {
                    // insert ok
                    d->new_tag_label = "";
                    d->new_tag_level = L_PRIMARY;
                    App->Bus()->postpone(AppEvent::TagEvent{ AppEvent::TagEvent::Add });
                }
                d->is_processing = false;
            });
    }
    ImGui::EndDisabled();
    ImGui::Separator();

    const float max_x = ImGui::GetContentRegionAvail().x;
    float used_x = 0;

    bool first_disabled = true;
    bool have_enabled_tags = false;

    enum Level {
        Undefined = -100,
        Primary = L_PRIMARY,
        Secondary = L_SECONDARY,
    };

    static const char* level_text[] {
        "主标签",
        "次标签",
    };

    int level = Undefined;

    // Render Tags
    for (auto& t : SqlViewOf(Tag))
    {
        static const char* btns_enabled[] // 对于已启用的标签
        {
            ICON_FA_PENCIL,
            ICON_FA_EYE_SLASH,
            ICON_FA_TRASH,
            nullptr
        };
        static const char* btns_disabled[] // 对于已禁用的标签
        {
            ICON_FA_PENCIL,
            ICON_FA_EYE,
            ICON_FA_TRASH,
            nullptr
        };

        if (level < (int)t.tag_level) {
            level = (int)t.tag_level;
            used_x = 0;
            ImGui::SeparatorText(level_text[t.tag_level % 0x2]);
        }

        if (!have_enabled_tags && !t.tag_disabled) {
            have_enabled_tags = true;
        }

        if (have_enabled_tags && first_disabled && t.tag_disabled) {
            ImGui::SeparatorText("已禁用的标签");
            used_x = 0;
            first_disabled = false;
        }

        auto btns = t.tag_disabled ? btns_disabled : btns_enabled;

        const auto w = ImGui::GetTagRenderWidth(t, btns) + ImGui::GetFontSize();
        if (used_x > 0 && max_x - used_x > w)
        {
            ImGui::SameLine();
        }
        else if (used_x > 0)
        {
            used_x = 0;
        }
        used_x += w;

        ImGui::RenderTag(t, btns, [this, editor_id](int id, void* data)
            {
                Tag* tag = (Tag*)data;
                if (id == 0)
                {
                    d->tag_copy = *tag;
                    d->current_tag = tag;
                    ImVec4 color = ImColor(tag->tag_color);
                    d->tag_color_copy[0] = color.x;
                    d->tag_color_copy[1] = color.y;
                    d->tag_color_copy[2] = color.z;
                    ImGui::OpenPopup(editor_id);
                }
                else if (id == 1) {
                    // Toggle enable/disable
                    App->Async([t = *tag] {
                        auto copy = t;
                        copy.tag_disabled ^= true;
                        if (App->Sql()->UpdateTag(copy)) {
                            App->Bus()->postpone(AppEvent::TagEvent{ AppEvent::TagEvent::Updated });
                        }
                    });
                }
                else if (id == 2) // delete
                {
                    App->Async([id = tag->tag_id]
                        {
                            if (bool success = App->Sql()->DeleteTag(id))
                            {
                                // delete ok
                                App->Bus()->postpone(AppEvent::TagEvent{ AppEvent::TagEvent::Delete });
                            }
                        });
                }
            }, (void*)&t);
    }

    ImGui::WindowBottomButtons(2, default_ok_cancel_button_text, [](int index, void*)
        {
            ImGui::CloseCurrentPopup();
        }, nullptr);

    // tag editor
    ImGui::SetNextWindowSize(ImVec2(ImGui::GetFontSize() * 28.f, ImGui::GetFontSize() * 16.f), ImGuiCond_Always);
    if (ImGui::BeginPopupModal("编辑标签##TagEditor", nullptr,
        ImGuiWindowFlags_NoMove |
        ImGuiWindowFlags_NoResize
    ))
    {
        IM_ASSERT(d->current_tag != nullptr);
        ImGui::AlignTextToFramePadding();
        ImGui::Text("标签名：");
        ImGui::InputText("##TAG_EDITOR_LABEL", &d->tag_copy.tag_name);
        //ImGui::TextUnformatted("标签颜色："); ImGui::SameLine();
        ImGui::ColorEdit3("标签颜色", d->tag_color_copy, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_DisplayRGB);
        bool primary_checked = d->tag_copy.tag_level == L_PRIMARY;
        if (ImGui::Checkbox("是否是一级标签？", &primary_checked))
        {
            if (primary_checked)
                d->tag_copy.tag_level = L_PRIMARY;
            else
                d->tag_copy.tag_level = L_SECONDARY;
        }
        ImGui::Checkbox("标签已禁用？", &d->tag_copy.tag_disabled);

        ImGui::WindowBottomButtons(2, default_ok_cancel_button_text, [this](int index, void*)
            {
                if (index == 0) // confirm
                {
                    d->current_tag = nullptr;
                    d->tag_copy.tag_color = ImU32(ImColor(d->tag_color_copy[0], d->tag_color_copy[1], d->tag_color_copy[2]));
                    App->Async([this]
                        {
                            bool ok = App->Sql()->UpdateTag(d->tag_copy);
                            if (ok)
                            {
                                App->Bus()->postpone(AppEvent::TagEvent{ AppEvent::TagEvent::Updated });
                            }
                        });
                }
                ImGui::CloseCurrentPopup();
            }, nullptr);
        ImGui::EndPopup();
    }
}
